package vcp.server.deamontasks;

import java.util.List;
import java.util.TimerTask;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import vcp.entity.Customer;
import vcp.entity.Subscription;
import vcp.server.DAO.CustomerDAO;
import vcp.server.DAO.SubscriptionDAO;
import vcp.server.interfaces.IServer;
import vcp.server.utility.CommunicationProvider;
import vcp.server.utility.SystemClock;

/**
 * 
 * @author VCP team
 *         <p>
 *         class that checks reserved lot if still not used and prepares to send
 *         reminder
 *         </p>
 */
public class ReservedLotReminderTask extends TimerTask
{
	private final IServer server;
	private final CommunicationProvider emailProvider;

	/**
	 * class constructor
	 * 
	 * @param serverDeamon
	 */
	public ReservedLotReminderTask ( IServer serverDeamon )
	{
		this.server = serverDeamon;
		this.emailProvider = new CommunicationProvider();
	}

	@Override
	public void run ()
	{
		synchronized (this.server.getDBLock())
		{
			System.out.println("ReservedLotReminderTask:  TrueTime:" + new DateTime() + "  SysTime:" + SystemClock.getClockInstance().getSystemDateTime());
			SubscriptionDAO subscriptionDAO = new SubscriptionDAO();
			List <Subscription> subscriptions = subscriptionDAO.findAllOrderAheadSubscribers();
			if ( subscriptions != null )
			{
				CustomerDAO customerDAO = new CustomerDAO();
				for ( Subscription subscription : subscriptions )
				{

					if ( SystemClock.getClockInstance().isTodayDate(subscription.getArrivalDate()) )
					{
						if ( SystemClock.getClockInstance().isCurrentTime(subscription.getArrivalDate()) )
						{
							Customer customer = customerDAO.findByID(subscription.getCustomerID());
							this.sendEmail(subscription, customer);
							// this.sendSMS(subscription, customer);
						}
					}
				}
			}
		}
	}

	/**
	 * sends email to customer
	 * 
	 * @param subscription
	 * @param customer
	 */
	private void sendEmail ( Subscription subscription, Customer customer )
	{
		System.out.println("Email was send to:" + customer.getUserFirstName() + " to email address:" + customer.getUserEmail());
		if ( customer.getBalance() == - 100 )
		{
			String emailBody =
					"Dear Mr.\\Mrs. " + customer.getUserLastName()
							+ "\n\n"
							+ "You reserved a parking space in VCP's " + subscription.getSite().toString()
							+ ", but yet have claimed your ordered parking space."
							+ "\n"
							+ "Your parking space will be preserved for another half of hour."
							+ "\n"
							+ "If you choose to keep your current reservation, you will be charged by a rate of extra 20%"
							+ " otherwise, your parking reservation will be canceled by today's "
							+ DateTimeFormat.forPattern("HH:mm").print(subscription.getArrivalDate())
							+ "\n\n"
							+ "Sincerely,"
							+ "\n"
							+ "VCP Inc.";

			this.emailProvider.sendEmail(subscription, customer, emailBody);
		}
	}
}
